package com.xuan.yubi.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 测试线程池的工作机制(只在开发环境生效)
 */
@RestController
@RequestMapping("/queue")
@Profile("dev")
@Slf4j
public class QueueController {

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("/add")
    public String addWork(String name) {
        CompletableFuture.runAsync(() -> {
            System.out.println("任务：" + name + "正在执行中，执行线程名称为：" + Thread.currentThread().getName());
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {

            }
        }, threadPoolExecutor);
        return "ok";
    }


    @GetMapping("/get")
    public Map<String, Object> workQueueInfo() {
        HashMap<String, Object> map = new LinkedHashMap<>();
        long taskCount = threadPoolExecutor.getTaskCount();
        map.put("当前任务总数", taskCount);
        int size = threadPoolExecutor.getQueue().size();
        map.put("当前工作队列任务数", size);
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        map.put("已完成的任务总数", completedTaskCount);
        int poolSize = threadPoolExecutor.getPoolSize();
        map.put("当前线程池中线程数量", poolSize);
        int activeCount = threadPoolExecutor.getActiveCount();
        map.put("正在工作的线程数量", activeCount);
        return map;
    }

}
